/*
 * BanBu_ListViewController
 * @description 本文件提供半圆项目附近的人的viewcontroller
 * @package
 * @author 		***
 * @copyright
 * @version 		1.0
 * @description 本文件提供半圆项目附近的人的viewcontroller
 */


#import "BanBu_ListViewController.h"
#import "BanBu_ListCell.h"
#import "BanBu_PersonDataViewController.h"
#import "AppDataManager.h"
#import "AppCommunicationManager.h"
#import "TKLoadingView.h"
#import "BanBu_HisFriendCell.h"
#import "BanBu_NavigationController.h"
#define HuaTag 111

#import "CJSONSerializer.h"
#import "CJSONDeserializer.h"
#import "BanBu_NavButton.h"
#import "BanBu_ImageView.h"
#import "LeveyTabBarController.h"
#import "BanBu_ThemeManager.h"
#import "BanBu_RefreshTime.h"
#import "UIViewController+Animation.h"
#import "BanBu_RecommentViewController.h"
#import "BanBu_ChoiceViewController.h"
#import "BanBu_PersonDataViewController.h"
#import "Banbu_NopushView.h"
#import "BanBu_WebViewController.h"
#import "BanBu_InviteFriendViewController.h"
#import "BanBu_RecomViewController.h"
@interface BanBu_ListViewController ()
{
    UIButton *sortBtn;
    BOOL showNoLocationNotice;
    BOOL showNoPushNotice;
    BOOL showNoNetwork;
    BOOL showInviteFriend;
    
    //附近推荐vip用户列表
    NSMutableArray * _recommendVipArr;
    NSInteger _linkRow;
}
@end

@implementation BanBu_ListViewController
@synthesize currentPage =_currentPage;
@synthesize DosPage = _DosPage;
@synthesize listType = _listType;
@synthesize badgeViewTalk = _badgeViewTalk;


- (void)dealloc
{
    [_recommendVipArr release];
    _recommendVipArr = nil;
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"toselect" object:nil];
    [self.tableView removeObserver:self forKeyPath:@"contentOffset"];
    [_existDic release],_existDic = nil;
    [lab release],lab = nil;
    [segmentController release],segmentController = nil;
    [moreView release];moreView = nil;
    self.badgeViewTalk = nil;
    [_nearbyNumLa release];
    _nearbyNumLa = nil;
    [_friendNumLa release];
    _friendNumLa = nil;
    [super dealloc];
}

#pragma mark - 更换主题之后更新segmentController的背景
-(void)changeTheme
{
    UIImage *backgroundImage = [ThemeManager getThemeImage:@"segmentTitle.png"];//[[ThemeManager getThemeImage:@"segmentTitle.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(10.0, 10.0, 10.0, 10.0)];
    
    [segmentController setBackgroundImage:backgroundImage];
}


#pragma mark - 初始化segmentController
- (void)setupSegmentedControl
{
    NSArray *titleArr = [NSArray arrayWithObjects:NSLocalizedString(@"luckPeopleTitle", nil), NSLocalizedString(@"friendShip2", nil),nil];
    UIImage *backgroundImage = [ThemeManager getThemeImage:@"segmentTitle.png"];//[ThemeManager getThemeImage:@"segmentTitle.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(10.0, 10.0, 10.0, 10.0)];
    
    [segmentController setBackgroundImage:backgroundImage];
    [segmentController setAutoresizingMask:UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleBottomMargin];
    
    UIImage *buttonBackgroundImagePressed_left = [UIImage imageNamed:@"segmented-bg-pressed_left.png"];
    UIImage *buttonBackgroundImagePressed_right = [UIImage imageNamed:@"segmented-bg-pressed_right.png"];
    // Button 1
    UIButton *buttonSocial = [[[UIButton alloc] init] autorelease];
    [buttonSocial setTitle:[titleArr objectAtIndex:1] forState:UIControlStateNormal];
    
    [buttonSocial setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [buttonSocial.titleLabel setFont:[UIFont fontWithName:@"HelveticaNeue-Bold" size:13.0]];
    buttonSocial.titleEdgeInsets = UIEdgeInsetsMake(-5, 0, 0, 0);
    [buttonSocial setBackgroundImage:buttonBackgroundImagePressed_right forState:UIControlStateHighlighted];
    [buttonSocial setBackgroundImage:buttonBackgroundImagePressed_right forState:UIControlStateSelected];
    [buttonSocial setBackgroundImage:buttonBackgroundImagePressed_right forState:(UIControlStateHighlighted|UIControlStateSelected)];
    
    // Button 2
    UIButton *buttonStar = [[[UIButton alloc] init] autorelease];
    
    [buttonStar setTitle:[titleArr objectAtIndex:0] forState:UIControlStateNormal];
    [buttonStar setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [buttonStar.titleLabel setFont:[UIFont fontWithName:@"HelveticaNeue-Bold" size:13.0]];
    buttonStar.titleEdgeInsets = UIEdgeInsetsMake(-5, 0, 0, 0);
    [buttonStar setBackgroundImage:buttonBackgroundImagePressed_left forState:UIControlStateHighlighted];
    [buttonStar setBackgroundImage:buttonBackgroundImagePressed_left forState:UIControlStateSelected];
    [buttonStar setBackgroundImage:buttonBackgroundImagePressed_left forState:(UIControlStateHighlighted|UIControlStateSelected)];
    
    friendOnline = [[UIImageView alloc] initWithFrame:CGRectMake(55,4, 8, 8)];
    [friendOnline setImage:[UIImage imageNamed:@"onlineFlag.png"]];
    [buttonStar addSubview:followOnline];
    friendOnline.hidden = YES;
    
    [segmentController setButtonsArray:@[buttonStar,buttonSocial]];
    //添加附近的人的气泡：yinlinlin：2014/07/08
    _badgeViewTalk = [[UIBadgeView alloc] init];
    
    _badgeViewTalk.backgroundColor = [UIColor clearColor];
    _badgeViewTalk.badgeColor = [UIColor redColor];
    [segmentController addSubview:_badgeViewTalk];
    [_badgeViewTalk setHidden:YES];
    _nearbyNumLa = [[UILabel alloc]initWithFrame:CGRectMake(0, 22, 100, 9)];
    _nearbyNumLa.textAlignment = kTextAlignmentCenter;
    _nearbyNumLa.backgroundColor = [UIColor clearColor];
    _nearbyNumLa.font = [UIFont systemFontOfSize:9.0];
    _nearbyNumLa.textColor = [UIColor whiteColor];
    [segmentController addSubview:_nearbyNumLa];
    _nearbyNumLa.text = [UserDefaults valueForKey:@"nearbysum"];
    _friendNumLa = [[UILabel alloc]initWithFrame:CGRectMake(96, 22, 100, 9)];
    _friendNumLa.textAlignment = kTextAlignmentCenter;
    _friendNumLa.backgroundColor = [UIColor clearColor];
    _friendNumLa.font = [UIFont systemFontOfSize:9.0];
    _friendNumLa.textColor = [UIColor whiteColor];
    [segmentController addSubview:_friendNumLa];
    
    //获取本地存储的个人信息,显示好友数量
    NSDictionary * friendsumDic = [[UserDefaults valueForKey:MyAppDataManager.useruid] valueForKey:@"friendsum"];
    NSInteger friendNum = [[friendsumDic valueForKey:@"g"] intValue] + [[friendsumDic valueForKey:@"h"] intValue];
    _friendNumLa.text = [NSString stringWithFormat:@"%d",friendNum];
    [self.navigationItem.titleView.superview bringSubviewToFront:self.navigationItem.titleView];
    self.navigationItem.titleView = segmentController;
    
}

-(void)setUserOnline:(NSNotification *)_not
{
    NSDictionary *dic = [_not object];
    
    friendOnline.hidden = ![[dic valueForKey:@"friendonline"] boolValue];
    followOnline.hidden = ![[dic valueForKey:@"followonline"] boolValue];
}
-(void)autoSetButtonStyle
{
    if(_sortByList)
    {
        
    }
}

#pragma mark - 判断是否显示推送 网络的提示信息
- (void)checkShowUserSettingError
{
    showNoPushNotice = NO;
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
    {
        UIUserNotificationType type1;
        type1 = [[UIApplication sharedApplication] currentUserNotificationSettings].types;
        if(type1 == UIUserNotificationTypeNone)
        {
            showNoPushNotice = YES;
            [UserDefaults setValue:@"" forKey:@"pushid"];
            //先判断缓存数据是否过期
            BOOL flag = [BanBu_CommUtils needUpdateCache:LastOpenNoficationTimeKey timeInterval:LastOpenNoficationTimeInterval];
            //已经过期
            if (flag)
            {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"openPush", nil) message:NSLocalizedString(@"howOpenPush", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"confirmNotice", nil) otherButtonTitles:nil, nil];
                
                [alert show];
                [alert release];
                
                [BanBu_CommUtils setCacheTime:LastOpenNoficationTimeKey];
            }
            
        }
    }
    else
    {
        UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
        if(types == UIRemoteNotificationTypeNone)
        {
            showNoPushNotice = YES;
            [UserDefaults setValue:@"" forKey:@"pushid"];
            //先判断缓存数据是否过期
            BOOL flag = [BanBu_CommUtils needUpdateCache:LastOpenNoficationTimeKey timeInterval:LastOpenNoficationTimeInterval];
            //已经过期
            if (flag)
            {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"openPush", nil) message:NSLocalizedString(@"howOpenPush", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"confirmNotice", nil) otherButtonTitles:nil, nil];
                
                [alert show];
                [alert release];
                
                [BanBu_CommUtils setCacheTime:LastOpenNoficationTimeKey];
            }
            
        }
    }
    showNoLocationNotice = NO;
    if (AppComManager.netStatus == NetReachableNone) {
        showNoNetwork = YES;
    }
    else{
        showNoNetwork = NO;
    }
}


#pragma mark - 断网提示，显示在上面的
-(void)showNetWOrkUnable:(NSNotification *)_notfi
{
    
    NetworkStatus status = [[_notfi object] integerValue];
    if(status == NotReachable)
    {
        showNoNetwork = YES;
    }
    else
    {
        showNoNetwork = NO;
    }
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];
    
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    showNoNetwork = NO;
    _recommendVipArr = [[NSMutableArray alloc]init];
    _existDic = [[NSMutableDictionary alloc]initWithCapacity:1];
    
    [self checkShowUserSettingError];
    showInviteFriend = NO;
    _firstRun = YES;
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(setUserOnline:) name:@"friendOnline" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(showNetWOrkUnable:) name:NetWork_Unable object:nil];
    
    if(MyAppDataManager.useruid.length)
    {
        [MyAppDataManager cleanUserOldBaseData];
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_async(queue, ^{
            NSMutableDictionary *userHaveSeen = [NSMutableDictionary dictionaryWithDictionary:[MyAppDataManager getUserBaseDataWithKey:keyUserHaveSeen]];
            NSString *usersString =[userHaveSeen valueForKey:@"users"];
            if(usersString.length>2000)
            {
                NSString *str = [usersString substringFromIndex:usersString.length-2000];
                [userHaveSeen setValue:str forKey:@"users"];
                
                [MyAppDataManager modifyUserBaseDataWithKey:keyUserHaveSeen andData:userHaveSeen];
            }
            
        });
    }
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTheme) name:kThemeDidChangeNotification object:nil];
    self.tabBarController.tabBar.frame = CGRectMake(0, __MainScreen_Height-44-50, 320, 50);
    alreadyRefresh = YES;
    isLoading      = NO;
    moreView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 80)];
    lab = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, 320,20)];
    lab.font= [UIFont systemFontOfSize:15];
    lab.backgroundColor =[UIColor colorWithRed:254.0/255.0 green:250.0/255.0 blue:239.0/255.0 alpha:1];
    lab.textAlignment = kTextAlignmentCenter;
    lab.textColor = [UIColor grayColor];
    lab.backgroundColor = [UIColor clearColor];
    moreView.backgroundColor = [UIColor clearColor];
    [moreView addSubview:lab];
    loadingView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    loadingView.hidden = NO;
    [loadingView setHidesWhenStopped:YES];
    loadingView.frame = CGRectMake(0, 0, 50, 50);
    loadingView.center = CGPointMake(160-([NSLocalizedString(@"loadingNotice", nil) sizeWithFont:[UIFont systemFontOfSize:15] constrainedToSize:CGSizeMake(320, 20) lineBreakMode:kTextLineBreakByWordWrapping].width/2)-15, 20);
    
    [moreView addSubview:loadingView];
    [loadingView release];
    
    [self setLoadingMore:NO];
    segmentController = [[AKSegmentedControl alloc] initWithFrame:CGRectMake(5,5,196,34)];
    [segmentController setDelegate:self];
    [self setupSegmentedControl];
    
    self.tableView.backgroundColor = [UIColor colorWithRed:255.0/255 green:250.0/255 blue:240.0/255 alpha:1.0];
    
    
    BanBu_ImageView *tableImage = [[[BanBu_ImageView alloc] initWithBackGroundImageType:UIImageViewCreatTypeTable] autorelease];
    self.tableView.backgroundView = tableImage;
    //    [tableImage release];
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    cacheArray = [[NSMutableArray alloc] initWithCapacity:20];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(tochange:) name:@"toselect" object:nil];
    [self buildLeftButton];
    
    _sortByList = YES;
    _currentPage = 0;
    
    
    
    
    sortBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    //    sortBtn.position = ButtonPositionRight;
    sortBtn.frame = CGRectMake(260, __MainScreen_Height-24-64, 40, 40);
    [sortBtn setImage:_sortByList?[UIImage imageNamed:@"grid.png"]:[UIImage imageNamed:@"list.png"] forState:UIControlStateNormal];
    
    //    [sortBtn setBackgroundColor:[UIColor colorWithRed:105.0/255.0 green:179.0/255.0 blue:233.0/255.0 alpha:0.8]];
    //    [sortBtn setImageEdgeInsets:UIEdgeInsetsMake(3.0, 5.0, 2.0, 3.0)];
    [sortBtn addTarget:self action:@selector(changeList:) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationController.view addSubview:sortBtn];
    
}

#pragma mark - 获取网络数据
- (void)banbuRequestDidFinished:(NSDictionary *)resDic error:(NSError *)error
{
    [loadingView stopAnimating];
    [TKLoadingView dismissTkFromView:self.view animated:YES afterShow:10.0];
    if(error)
    {
        if([error.domain isEqualToString:BanBuDataformatError])
        {
            [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"network_error", nil) activityAnimated:NO duration:2.0];
            [loadingView stopAnimating];
            lab.text = NSLocalizedString(@"network_error", nil);
        }
        else
        {
            [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"network_error", nil) activityAnimated:NO duration:2.0];
            [loadingView stopAnimating];
            lab.text = NSLocalizedString(@"network_error", nil);
            
        }
        [loadingView stopAnimating];
        if(_currentPage>3)
        {
            _currentPage--;
        }
        else
        {
            _currentPage =1;
        }
        isLoading      = NO;
        [self finishedLoading];
        //        if(_isLoadingMore)
        //            _currentPage --;
        return;
    }
    //获取推荐列表
    if([AppComManager respondsDic:resDic isFunctionData:Banbu_Get_Vipuser_Nearby])
    {
        if ([resDic valueForKey:@"list"] && ([[resDic valueForKey:@"list"] isKindOfClass:[NSArray class]]))
        {
            NSArray *listArr = resDic[@"list"];
            [_recommendVipArr addObjectsFromArray:listArr];
            [self.tableView reloadData];
        }
        return;
    }
    if([AppComManager respondsDic:resDic isFunctionData:BanBu_Get_User_Nearby]||[AppComManager respondsDic:resDic isFunctionData:BanBu_Get_User_Nearmy])
    {
        
        //更新附近的人的数量
        //        NSString * talkStr = [resDic valueForKey:@"nearbysum"];
        _nearbyNumLa.text = [resDic valueForKey:@"nearbysum"];
        //附近的人缓存
        [UserDefaults setValue:[resDic valueForKey:@"nearbysum"] forKey:@"nearbysum"];
        //获取本地存储的个人信息,显示好友数量
        NSDictionary * friendsumDic = [[UserDefaults valueForKey:MyAppDataManager.useruid] valueForKey:@"friendsum"];
        NSInteger friendNum = [[friendsumDic valueForKey:@"g"] intValue] + [[friendsumDic valueForKey:@"h"] intValue];
        _friendNumLa.text = [NSString stringWithFormat:@"%d",friendNum];
        //        [loadingView stopAnimating];
        [self performSelector:@selector(setSegmentUserInterface) withObject:nil afterDelay:0.5];
        if (![[resDic valueForKey:@"list"]count])
        {
            lab.text = NSLocalizedString(@"noData", nil);
        }
        
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        if([[resDic valueForKey:@"servertime"] length])
        {
            MyAppDataManager.timeDifference = [[formatter dateFromString:[NSString stringWithFormat:@"%@",[resDic valueForKey:@"servertime"]]] timeIntervalSinceNow];
            [UserDefaults setObject:[NSNumber numberWithDouble:MyAppDataManager.timeDifference] forKey:@"timedifference"];
        }
        else
        {
            MyAppDataManager.timeDifference = [[UserDefaults valueForKey:@"timedifference"] doubleValue];
        }
        [formatter release];
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            if([AppComManager respondsDic:resDic isFunctionData:BanBu_Get_User_Nearby]||[AppComManager respondsDic:resDic isFunctionData:BanBu_Get_User_Nearmy])
            {
                
                [loadingView stopAnimating];
                if([[resDic valueForKey:@"ok"] boolValue])
                {
                    
                    //去除黑名单的人
                    NSString *flistString = [NSString stringWithFormat:@",%@,%@,",[[[UserDefaults valueForKey:MyAppDataManager.useruid] valueForKey:@"friendlist"] valueForKey:@"x"],[[[UserDefaults valueForKey:MyAppDataManager.useruid] valueForKey:@"friendlist"] valueForKey:@"z"]];
                    
                    
                    if(_isLoadingRefresh)
                    {
                        
                        NSNumber * number = [NSNumber numberWithInt:[[resDic valueForKey:@"getscore"] integerValue]];
                        dispatch_sync(dispatch_get_main_queue(), ^{
                            [MyAppDataManager showGoldView:number andView:self.navigationController.view];
                        });
                        
                        //存储刷新的最后时间
                        [BanBu_RefreshTime getCurrentTime:@"nearby_updateTime"];
                        [AppComManager cancalHandleNemed:@"" forObject:@""];
                        //                [self finishedLoading];
                        [MyAppDataManager.nearBuddys removeAllObjects];
                        [cacheArray removeAllObjects];
                        //对名字和话，进行替换后 ，在存储
                        [_existDic removeAllObjects];
                        NSMutableArray *saveArr = [[NSMutableArray alloc] init];
                        for(int i=0;i<[[resDic valueForKey:@"list"]count];i++)
                        {
                            @autoreleasepool {
                                NSMutableDictionary *aDic = [NSMutableDictionary dictionaryWithCapacity:0];
                                
                                [aDic addEntriesFromDictionary:[[resDic valueForKey:@"list"] objectAtIndex:i]];
                                
                                NSMutableDictionary *personalData = [NSMutableDictionary dictionaryWithCapacity:0];
                                [personalData addEntriesFromDictionary:[aDic valueForKey:keyPersonalInfo]];
                                
                                
                                if([MyAppDataManager theRevisedName:[[aDic valueForKey:keyPersonalInfo] valueForKey:@"pname"] andUID:[aDic valueForKey:@"userid"]])
                                {
                                    [personalData setObject:[MyAppDataManager theRevisedName:[personalData valueForKey:@"pname"]andUID:[aDic valueForKey:@"userid"]] forKey:@"pname"];
                                    [_existDic setObject:[NSNumber numberWithBool:YES] forKey:[aDic valueForKey:@"userid"]];
                                    [aDic setObject:personalData forKey:keyPersonalInfo];
                                }
                                if(MyAppDataManager.nearBuddys.count<20)
                                {
                                    [MyAppDataManager.nearBuddys addObject:aDic];
                                }
                                else
                                {
                                    [cacheArray addObject:aDic];
                                }
                                [saveArr addObject:aDic];
                                
                            }
                        }
                        dispatch_sync(dispatch_get_main_queue(), ^{
                            [self.tableView reloadData];
                        });
                        
                        //                /*测试代码*/
                        //                [MyAppDataManager.nearBuddys removeAllObjects];
                        //                /*测试代码*/
                        
                        if(!MyAppDataManager.nearBuddys.count)
                        {
                            
                            dispatch_sync(dispatch_get_main_queue(), ^{
                                if(segmentController.selectedIndex == 1)
                                {
                                }
                                else
                                {
                                    cryImageView = [[UIImageView alloc]initWithFrame:CGRectMake(136, 100, 48, 48)];
                                    cryImageView.tag = 100;
                                    cryImageView.image = [UIImage imageNamed:@"cry.png"];
                                    [self.tableView addSubview:cryImageView];
                                    [cryImageView release];
                                    noticeLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 150, 300, 100)];
                                    noticeLabel.tag = 101;
                                    noticeLabel.numberOfLines = 0;
                                    noticeLabel.text = NSLocalizedString(@"noticeLabel", nil);
                                    noticeLabel.font = [UIFont systemFontOfSize:16];
                                    noticeLabel.textAlignment = kTextAlignmentCenter;
                                    noticeLabel.backgroundColor = [UIColor clearColor];
                                    noticeLabel.textColor = [UIColor darkGrayColor];
                                    [self.tableView addSubview:noticeLabel];
                                    [noticeLabel release];
                                    [moreView removeFromSuperview];
                                }
                                
                                
                            });
                        }
                        else
                        {
                            
                            NSData *listDataCopy = [NSKeyedArchiver archivedDataWithRootObject:MyAppDataManager.nearBuddys];
                            NSString *path = [DataCachePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@-nearbuddydata",MyAppDataManager.useruid]];
                            [listDataCopy writeToFile:path atomically:YES];
                            dispatch_sync(dispatch_get_main_queue(), ^{
                                [self.tableView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:self.tableView];
                                self.tableView.tableFooterView = moreView;
                            });
                            NSArray *saveArray = [[NSArray alloc] initWithArray:saveArr];
                            //
                            [MyAppDataManager writePersonalDataToDB:saveArray];
                            
                        }
                        [saveArr release];
                    }
                    else
                    {
                        //                NSLog(@"%@",resDic);
                        //                NSLog(@"_________________________%@",_existDic);
                        NSMutableArray *filterArr = [NSMutableArray arrayWithArray:[resDic valueForKey:@"list"]];
                        
                        NSMutableArray *congfuArr = [NSMutableArray array];
                        for(int i=0;i<[filterArr count];i++)
                        {
                            BOOL isBlack = NO;
                            if(flistString.length&&[flistString rangeOfString:[[filterArr objectAtIndex:i] valueForKey:@"userid"]].location != NSNotFound)
                            {
                                isBlack = YES;
                            }
                            if(isBlack)
                            {
                                [congfuArr addObject:[filterArr objectAtIndex:i]];
                            }
                            //修改去重******************
                            if(_existDic&&[_existDic valueForKey:[[filterArr objectAtIndex:i] valueForKey:@"userid"]])
                            {
                                [congfuArr addObject:[filterArr objectAtIndex:i]];
                            }
                            else
                            {
                                NSMutableDictionary *aDic = [NSMutableDictionary dictionaryWithDictionary:[filterArr objectAtIndex:i]];
                                NSMutableDictionary *personData = [[NSMutableDictionary alloc] initWithDictionary:[aDic valueForKey:keyPersonalInfo]];
                                if([MyAppDataManager theRevisedName:[aDic valueForKey:@"pname"] andUID:[aDic valueForKey:@"userid"]])
                                {
                                    [personData setObject:[MyAppDataManager theRevisedName:[aDic valueForKey:@"pname"] andUID:[aDic valueForKey:@"userid"]] forKey:@"pname"];
                                    [aDic setObject:personData forKey:keyPersonalInfo];
                                    [filterArr replaceObjectAtIndex:i withObject:aDic];
                                }
                                [personData release];
                            }
                            [_existDic setObject:[NSNumber numberWithBool:YES] forKey:[[filterArr objectAtIndex:i] objectForKey:@"userid"]];
                        }
                        [cacheArray removeAllObjects];
                        [filterArr removeObjectsInArray:congfuArr];
                        [cacheArray addObjectsFromArray:filterArr];
                        
                        if(!alreadyRefresh&&isLoading&&cacheArray.count)
                        {
                            dispatch_sync(dispatch_get_main_queue(), ^{
                                [self startLoadNextPage];
                            });
                        }
                        NSMutableArray *saveArr = [[NSMutableArray alloc] initWithArray:cacheArray];
                        [MyAppDataManager writePersonalDataToDB:saveArr];
                        [saveArr release];
                    }
                }
                else
                {
                    [loadingView stopAnimating];
                    if(_currentPage>3)
                    {
                        _currentPage--;
                    }
                    else
                    {
                        _currentPage =1;
                    }
                    [loadingView stopAnimating];
                    lab.text = NSLocalizedString(@"noData", nil);
                    //            if(_isLoadingRefresh)
                    //            [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"network_error", nil) activityAnimated:NO duration:2.0];
                }
                if(MyAppDataManager.nearBuddys.count<10)
                {
                    dispatch_sync(dispatch_get_main_queue(), ^{
                        self.tableView.tableFooterView = [[[UIView alloc] initWithFrame:moreView.frame] autorelease];
                    });
                }
                
                if(MyAppDataManager.nearBuddys.count<10)
                {
                    [self showInviteFriendEnable];
                    if(segmentController.selectedIndex == 1)
                    {
                        //                    [self updateNoFriendView];
                        if (!_recommendVipArr.count) {
                            [self getRecommendList];
                        }
                    }
                }
                
            }
            //    if([AppComManager respondsDic:resDic isFunctionData:BanBu_Get_User_Nearmy])
            dispatch_sync(dispatch_get_main_queue(), ^{
                [self finishedLoading];
            });
            
            isLoading = NO;
        });
        return;
    }
    else if([AppComManager respondsDic:resDic isFunctionData:BanBu_Set_Friend_Link])
    {
        self.view.userInteractionEnabled = YES;
        if([[resDic valueForKey:@"ok"]boolValue])
        {
            NSMutableDictionary *uidDic = [NSMutableDictionary dictionaryWithDictionary:[UserDefaults valueForKey:MyAppDataManager.useruid]];
            [uidDic setValue:[resDic valueForKey:@"friendlist"] forKey:FriendShip];
            
            [UserDefaults setValue:uidDic forKey:MyAppDataManager.useruid];
            [UserDefaults synchronize];
            
            NSMutableDictionary *aDic = [NSMutableDictionary dictionaryWithDictionary:[_recommendVipArr objectAtIndex:_linkRow]];
            [aDic setValue:[NSNumber numberWithBool:YES] forKey:@"linked"];//是否关注
            [_recommendVipArr replaceObjectAtIndex:_linkRow withObject:aDic];
            [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:_linkRow inSection:2]] withRowAnimation:UITableViewRowAnimationNone];
            
            
            BanBu_HisFriendCell *cell = (BanBu_HisFriendCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:_linkRow inSection:2]];
            [cell.linkBtn removeTarget:self action:@selector(addLink:) forControlEvents:UIControlEventTouchUpInside];
            
            [TKLoadingView dismissTkFromView:self.navigationController.view animated:NO afterShow:0];
            [TKLoadingView showTkloadingAddedTo:self.navigationController.view point:CGPointMake(0, 190) title:NSLocalizedString(@"linkSuccess", nil) activityAnimated:NO duration:1.0];
            
        }
        else
        {
            [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:[MyAppDataManager IsInternationalLanguage:[resDic valueForKey:@"error"]] activityAnimated:NO duration:1.0];
        }
    }
}

#pragma mark - 点击segment切换时navigationbar左侧的按钮更换(排序和筛选)
-(void)buildLeftButton
{
    if(segmentController.selectedIndex == 0)
    {
        // 筛选的
        BanBu_NavButton *selectButton = [[BanBu_NavButton alloc] initWithButtonType:UIButtonCreatTypeNormal];
        selectButton.position = ButtonPositionLeft;
        [selectButton setImage:[UIImage imageNamed:@"searchby.png"] forState:UIControlStateNormal];
        selectButton.titleLabel.font=[UIFont systemFontOfSize:15];
        selectButton.frame=CGRectMake(0, 0, 40, 30);
        [selectButton addTarget:self action:@selector(toSelsect:) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *leftButton = [[[UIBarButtonItem alloc] initWithCustomView:selectButton] autorelease];
        self.navigationItem.leftBarButtonItem = leftButton;
        [selectButton release];
    }
    else
    {
        BanBu_NavButton *selectButton = [[BanBu_NavButton alloc] initWithButtonType:UIButtonCreatTypeNormal];
        selectButton.position = ButtonPositionLeft;
        [selectButton setImage:[UIImage imageNamed:@"sort.png"] forState:UIControlStateNormal];
        
        selectButton.frame=CGRectMake(0, 0, 40, 30);
        [selectButton addTarget:self action:@selector(toSelsect:) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *leftButton = [[[UIBarButtonItem alloc] initWithCustomView:selectButton] autorelease];
        self.navigationItem.leftBarButtonItem = leftButton;
        [selectButton release];
    }
    
}

#pragma mark - 点击segment附近的人右侧筛选按钮
-(void)toSelsect:(UIButton *)sender
{
    if(segmentController.selectedIndex == 0)
    {
        
        BanBu_choiceController *choice=[[BanBu_choiceController alloc]init];
        
        BanBu_NavigationController *nav=[[[BanBu_NavigationController alloc]initWithRootViewController:choice] autorelease];
        
        nav.modalPresentationStyle=UIModalPresentationPageSheet;
        
        [self presentViewController:nav animated:YES];
        [self.leveyTabBarController hidesTabBar:YES animated:YES];
        [choice release];
    }
    else
    {
        UIActionSheet *act = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:NSLocalizedString(@"取消", nil) destructiveButtonTitle:nil otherButtonTitles:NSLocalizedString(@"sortByInstance", nil),NSLocalizedString(@"sortByOnline", nil), nil];
        [act showInView:self.view];
        [act release];
    }
    
}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(buttonIndex == actionSheet.cancelButtonIndex)
    {
        return;
    }
    NSMutableDictionary *dic;
    
    if([UserDefaults valueForKey:[NSString stringWithFormat:@"%@electNearBy",MyAppDataManager.useruid]])
    {
        dic=[NSMutableDictionary dictionaryWithDictionary:[UserDefaults valueForKey:[NSString stringWithFormat:@"%@electNearBy",MyAppDataManager.useruid]]];
    }
    else
    {
        dic=[NSMutableDictionary dictionaryWithCapacity:1];
    }
    
    if(buttonIndex==0)
    {
        
        [dic setValue:@"juli" forKey:@"orderby"];
    }
    else
    {
        [dic setValue:@"shi" forKey:@"orderby"];
    }
    [UserDefaults setValue:dic forKey:[NSString stringWithFormat:@"%@electNearBy",MyAppDataManager.useruid]];
    [self setRefreshing];
}
-(void)tochange:(NSNotification *)notif
{
    [self setRefreshing];
}
-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:YES];
    
    
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    BanBu_SmallListView *listView = (BanBu_SmallListView *)[self.navigationController.view viewWithTag:1021];
    sortBtn.hidden = YES;
    if(listView)
    {
        [listView dismissWithAnimation:YES];
    }
}


-(void)viewWillAppear:(BOOL)animated
{
    [UIView setAnimationsEnabled:YES];
    [super viewWillAppear:animated];
    [self.tableView reloadRowsAtIndexPaths:[self.tableView indexPathsForVisibleRows] withRowAnimation:UITableViewRowAnimationNone];
    sortBtn.hidden = NO;
    [self.leveyTabBarController hidesTabBar:NO animated:YES];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    self.tableView.tableFooterView = moreView;
    if((!MyAppDataManager.nearBuddys.count || !_currentPage)&&!_isLoadingRefresh&&_firstRun)
    {
        [self setRefreshing];
        return;
    }
    //    AppLocationManager.delegate = self;
    
    //判断是否要刷新页面
    NSString *timeNowString = [BanBu_RefreshTime getCurrentTime:nil];
    BOOL isReload = [BanBu_RefreshTime now:timeNowString isLaterBefore:[UserDefaults valueForKey:@"nearby_updateTime"]];
    if(isReload)
    {
        [segmentController setSelectedIndex:0];
        //       [self setRefreshing];
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)sort:(UIButton *)button
{
    BanBu_SmallListView *listView = (BanBu_SmallListView *)[self.navigationController.view viewWithTag:1021];
    if(listView)
    {
        [listView dismissWithAnimation:YES];
        return;
    }
    BanBu_SmallListView *smallList = [[BanBu_SmallListView alloc] initWithFrame:CGRectMake(0, 0, 95, 100) listTitles:[NSArray arrayWithObjects:NSLocalizedString(@"listTitle", nil),NSLocalizedString(@"listTitle1", nil),NSLocalizedString(@"listTitle2", nil), nil]];
    smallList.tag = 1021;
    smallList.delegate = self;
    smallList.selectedIndex = _listType;
    [smallList showFromPoint:CGPointMake(0.0, 65) inView:self.navigationController.view animation:YES];
    [smallList release];
}

- (void)changeList:(UIButton *)button
{
    _sortByList = !_sortByList;
    [moreView setFrame:CGRectMake(0, self.tableView.frame.size.height, 320, 80)];
    //    [button setImage:_sortByList?[UIImage imageNamed:@"button_grid.png"]:[UIImage imageNamed:@"button_list.png"] forState:UIControlStateNormal];
    [button setImage:_sortByList?[UIImage imageNamed:@"grid.png"]:[UIImage imageNamed:@"list.png"] forState:UIControlStateNormal];
    
    
    [UIView beginAnimations:@"change" context:nil];
    [UIView setAnimationDuration:0.5f];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationRepeatAutoreverses:NO];
    [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:self.tableView cache:YES];
    [self.tableView reloadData];
    [UIView commitAnimations];
}

#pragma mark - 获取推荐附近vip列表
- (void)getRecommendList
{
    //想要请求的附近vip的用户的性别
    NSString * wantGender;
    if ([[[UserDefaults valueForKey:MyAppDataManager.useruid] valueForKey:@"gender"] isEqualToString:@"m"])
    {
        wantGender = @"f";
    }
    else
    {
        wantGender = @"m";
    }
    NSDictionary *parDic = [NSDictionary dictionaryWithObjectsAndKeys:@"30",@"countof",wantGender,@"gender",nil];
    [AppComManager getBanBuData:Banbu_Get_Vipuser_Nearby par:parDic delegate:self];
    [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"loadingNotice", nil) activityAnimated:YES];
}
#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    //    return 3; //section 0 为未开启定位 断网的等等的各种服务提示
    if (_recommendVipArr.count > 0 && segmentController.selectedIndex == 0)
    {
        return 3;
    }
    else
    {
        return 2;
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    //每次多获取20条供下一页准备
    if(section == 0)
    {
        return 1;
    }
    if (section == 2)
    {
        return _recommendVipArr.count;
    }
    if(_sortByList)
    {
        return [MyAppDataManager.nearBuddys count];
    }
    else
    {
        if([MyAppDataManager.nearBuddys count]%4!=0){
            
            gridViewRow = ([MyAppDataManager.nearBuddys count])/4+1;
        }else{
            gridViewRow = ([MyAppDataManager.nearBuddys count])/4;
        }
        return gridViewRow;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0)
    {
        if(showNoPushNotice||showNoLocationNotice||showNoNetwork||showInviteFriend)
        {
            return 50;
        }
        else
        {
            return 0;
            
        }
    }
    if(indexPath.section == 2)
    {
        return 64;
    }
    if(_sortByList)
        return 84;
    else
        return 79;
}

-(void)dismissWarningView{
    CGRect frame = self.tableView.frame;
    [UIView animateWithDuration:0.2f animations:^{
        CGRect f = frame;
        f.origin.y = f.origin.y - 50;
        self.tableView.frame = f;
    } completion:^(BOOL finished) {
        self.tableView.tableHeaderView = nil;
        
        self.tableView.frame = frame;
        [self.tableView reloadData];
    }];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0)
    {
        static NSString *indentifier = @"headerercellcellIndentifier";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:indentifier];
        if(cell == nil)
        {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indentifier] autorelease];
        }
        else
        {
            for(UIView *sub in cell.contentView.subviews)
            {
                [sub removeFromSuperview];
            }
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        if(showNoPushNotice)
        {
            Banbu_NopushView *nopush = [Banbu_NopushView shareView] ;
            nopush.frame = CGRectMake(0, 0, 320, 50);
            [nopush setNoticeType:NoticeOpenTypePush];
            [cell.contentView addSubview:nopush];
            
            __block Banbu_NopushView *push = nopush;
            __block BanBu_ListViewController *bself = self;
            [push setDismiss:^(UIButton *btn) {
                
                showNoPushNotice = NO;
                if(showNoLocationNotice||showInviteFriend||showNoNetwork)
                {
                    [self.tableView reloadData];
                    
                }
                else
                {
                    [self dismissWarningView];
                }
                
                
            }];
            [push setOpen:^(UIButton *btn) {
                
                BanBu_WebViewController *web = [[BanBu_WebViewController alloc] initWIthType:NoticeOpenTypePush];
                [self.navigationController pushViewController:web animated:YES];
                [web release];
                [bself.leveyTabBarController hidesTabBar:YES animated:YES];
                
                showNoPushNotice = NO;
                [push removeFromSuperview];
                [bself.tableView reloadData];
            }];
            
        }
        
        if(showNoLocationNotice)
        {
            Banbu_NopushView *nolocation = [Banbu_NopushView shareView] ;
            nolocation.frame = CGRectMake(0, 0, 320, 50);
            
            [nolocation setNoticeType:NoticeOpenTypeLocation];
            [cell.contentView addSubview:nolocation];
            __block Banbu_NopushView *loc = nolocation;
            __block BanBu_ListViewController *bself = self;
            
            [loc setDismiss:^(UIButton *btn) {
                
                showNoLocationNotice = NO;
                if(showNoPushNotice||showNoNetwork||showInviteFriend)
                {
                    [self.tableView reloadData];
                }
                else
                {
                    [self dismissWarningView];
                }
                
                
            }];
            [loc setOpen:^(UIButton *btn) {
                [loc removeFromSuperview];
                BanBu_WebViewController *web = [[BanBu_WebViewController alloc] initWIthType:NoticeOpenTypeLocation];
                [self.navigationController pushViewController:web animated:YES];
                [web release];
                [bself.leveyTabBarController hidesTabBar:YES animated:YES];
                
                showNoLocationNotice = NO;
                [bself.tableView reloadData];
            }];
        }
        if(showNoNetwork)
        {
            Banbu_NopushView *nolocation = [Banbu_NopushView shareView] ;
            nolocation.frame = CGRectMake(0, 0, 320, 50);
            
            [nolocation setNoticeType:NoticeOpenTypeNetwork];
            [cell.contentView addSubview:nolocation];
            __block Banbu_NopushView *loc = nolocation;
            __block BanBu_ListViewController *bself = self;
            
            [loc setDismiss:^(UIButton *btn) {
                
                showNoNetwork = NO;
                if(showNoPushNotice||showNoLocationNotice||showInviteFriend) //判断是否只有这一个提示 如果下面还有其他提示 直接刷新 不用对table加动画
                {
                    [bself.tableView reloadData];
                }
                else
                {
                    [bself dismissWarningView];
                }
            }];
            [loc setOpen:^(UIButton *btn) {
                [loc removeFromSuperview];
                BanBu_WebViewController *web = [[BanBu_WebViewController alloc] initWIthType:NoticeOpenTypeNetwork];
                [self.navigationController pushViewController:web animated:YES];
                [web release];
                [bself.leveyTabBarController hidesTabBar:YES animated:YES];
                
                showNoNetwork = NO;
                [bself.tableView reloadData];
            }];
        }
        if(showInviteFriend)
        {
            Banbu_NopushView *inviteFriend = [Banbu_NopushView shareView] ;
            inviteFriend.frame = CGRectMake(0, 0, 320, 50);
            
            [inviteFriend setNoticeType:NoticeOpenTypeInviteFriend];
            [cell.contentView addSubview:inviteFriend];
            __block Banbu_NopushView *inv = inviteFriend;
            __block BanBu_ListViewController *bself = self;
            
            [inv setDismiss:^(UIButton *btn) {
                
                showInviteFriend = NO;
                if(showNoPushNotice||showNoLocationNotice||showNoNetwork) //判断是否只有这一个提示 如果下面还有其他提示 直接刷新 不用对table加动画
                {
                    [bself.tableView reloadData];
                }
                else
                {
                    [bself dismissWarningView];
                }
            }];
            [inv setOpen:^(UIButton *btn) {
                [bself inviteFriend];
                [inv removeFromSuperview];
            }];
        }
        
        return cell;
    }
    if(indexPath.section == 2)
    {
        static NSString *cellIndentifier = @"hisFriendCellIndentifier";
        BanBu_HisFriendCell *cell = (BanBu_HisFriendCell *)[tableView dequeueReusableCellWithIdentifier:cellIndentifier];
        if(!cell)
        {
            cell = [[[BanBu_HisFriendCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentifier] autorelease];
            //        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        NSDictionary *buddy = [_recommendVipArr objectAtIndex:indexPath.row];
        [cell updateHisFriendCell:buddy];
        if([[buddy valueForKey:@"linked"] boolValue]) //是否关注
        {
            [cell.linkBtn setBackgroundImage:[ThemeManager getThemeImage:@"app_button_welcomelogin.png"] forState:UIControlStateNormal];
            [cell.linkBtn setBackgroundImage:[ThemeManager getThemeImage:@"app_button_welcomelogin.png"] forState:UIControlStateHighlighted];
            [cell.linkBtn setTitle:@"+" forState:UIControlStateNormal];
            //                cell.linkBtn.hidden = YES;
        }
        else
        {
            [cell.linkBtn setBackgroundImage:[ThemeManager getThemeImage:@"app_btn_blue.png"] forState:UIControlStateNormal];
            cell.linkBtn.userInteractionEnabled = YES;
            [cell.linkBtn setTitle:@"+" forState:UIControlStateNormal];
            cell.linkBtn.tag = indexPath.row+222;
            [cell.linkBtn addTarget:self action:@selector(addLink:) forControlEvents:UIControlEventTouchUpInside];
            
        }
        
        return cell;
    }
    if(_sortByList)
    {
        static NSString *ListCellIdentifier = @"ListCellIdentifier";
        BanBu_ListCell *cell = (BanBu_ListCell *)[tableView dequeueReusableCellWithIdentifier:ListCellIdentifier];
        if(cell == nil)
        {
            cell = [[[BanBu_ListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ListCellIdentifier] autorelease];
        }
        if(MyAppDataManager.nearBuddys.count-1<indexPath.row)
        {
            return cell;
        }
        if(MyAppDataManager.nearBuddys.count)
        {
            if([[MyAppDataManager.nearBuddys valueForKey:keyPersonalInfo] count])
            {
                NSDictionary *buddy = [MyAppDataManager.nearBuddys objectAtIndex:indexPath.row];
                if(!buddy.count)
                {
                    return cell;
                }
                [cell updateListCell:buddy];
            }
        }
        return cell;
    }
    else
    {
        static NSString *GridCellIdentifier = @"GridCellIdentifier";
        BanBu_GridCell *cell = (BanBu_GridCell *)[tableView dequeueReusableCellWithIdentifier:GridCellIdentifier];
        if(cell == nil)
        {
            cell = [[[ BanBu_GridCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:GridCellIdentifier] autorelease];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.delegate = self;
        }
        
        if(cell.contentView.subviews.count){
            for(UIButton *temp in cell.contentView.subviews){
                temp.hidden = YES;
            }
        }
        cell.backgroundColor = [UIColor clearColor];
        cell.contentView.backgroundColor = [UIColor clearColor];
        if(gridViewRow-1 == indexPath.row && MyAppDataManager.nearBuddys.count%4 != 0){
            for (int i=0; i<MyAppDataManager.nearBuddys.count%4; i++)
            {
                NSDictionary *personDic=[MyAppDataManager.nearBuddys objectAtIndex:i+indexPath.row*4];
                [cell setImage:[[personDic valueForKey:keyPersonalInfo] valueForKey:@"uface"] distance:[[personDic valueForKey:keyPersonalInfo]valueForKey:@"dmeter"] sex:[[personDic valueForKey:keyPersonalInfo] valueForKey:@"gender"] flag:NO forTile:i name:[MyAppDataManager IsInternationalLanguage:[[personDic valueForKey:keyPersonalInfo] valueForKey:@"pname"]] onlineTime:[MyAppDataManager getTheSecondLastOnlineTime:[[personDic valueForKey:keyPersonalInfo] valueForKey:@"ltime"]] vip:[[[personDic valueForKey:keyPersonalInfo] valueForKey:@"userlevel"] integerValue]>0 verify:[[[personDic valueForKey:keyPersonalInfo] valueForKey:@"verify"] boolValue]];
            }
        }
        else{
            for (int i=0; i<4; i++)
            {
                NSDictionary *personDic=[MyAppDataManager.nearBuddys objectAtIndex:i+indexPath.row*4];
                [cell setImage:[[personDic valueForKey:keyPersonalInfo] valueForKey:@"uface"] distance:[[personDic valueForKey:keyPersonalInfo]valueForKey:@"dmeter"] sex:[[personDic valueForKey:keyPersonalInfo] valueForKey:@"gender"] flag:NO forTile:i name:[[personDic valueForKey:keyPersonalInfo]valueForKey:@"pname"] onlineTime:[MyAppDataManager getTheSecondLastOnlineTime:[[personDic valueForKey:keyPersonalInfo] valueForKey:@"ltime"]] vip:[[[personDic valueForKey:keyPersonalInfo] valueForKey:@"userlevel"] integerValue]>0 verify:[[[personDic valueForKey:keyPersonalInfo] valueForKey:@"verify"] boolValue]];
            }
        }
        
        return  cell;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 2)
    {
        return 36;
    }
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section < 2)
    {
        return nil;
    }
    UIView * headerV = [[[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 36)]autorelease];
    headerV.backgroundColor = UIColorWithRGB(237, 239, 231, 1.0);
    UILabel * recommendLa = [[UILabel alloc]initWithFrame:CGRectMake(10, 8, 300, 20)];
    recommendLa.text = NSLocalizedString(@"recomment", nil);
    NSLog(@"recommendLa.text:%@",recommendLa.text);
    recommendLa.font = [UIFont systemFontOfSize:14.0];
    [headerV addSubview:recommendLa];
    [recommendLa release];
    return headerV;
}
#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0)
    {
        return;
    }
    if (indexPath.section == 2)
    {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        NSDictionary *buddy = [_recommendVipArr objectAtIndex:indexPath.row];
        if([[[buddy valueForKey:keyPersonalInfo] valueForKey:@"pname"]length])
        {
            BanBu_PersonDataViewController *peopleFfofile = [[BanBu_PersonDataViewController alloc] initWithProfile:[buddy valueForKey:keyPersonalInfo]];
            [self.leveyTabBarController hidesTabBar:YES animated:YES];
            [self.navigationController pushViewController:peopleFfofile animated:YES];
            [peopleFfofile release];
        }
        
    }
    if(indexPath.section == 1)
    {
        [self.navigationController setNavigationBarHidden:NO animated:NO];
        NSDictionary *buddy = [MyAppDataManager.nearBuddys objectAtIndex:indexPath.row];
        
        
        BanBu_PersonDataViewController *peopleFfofile = [[BanBu_PersonDataViewController alloc] initWithProfile:[buddy valueForKey:keyPersonalInfo]];
        [self.leveyTabBarController hidesTabBar:YES animated:YES];
        [self.navigationController pushViewController:peopleFfofile animated:YES];
        [peopleFfofile release];
    }
}



-(void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0 || indexPath.section == 2) {return;}
    
    if(cell)
    {
        [(BanBu_ListCell *)cell cancelImageLoad];
    }
}


#pragma mark - 添加附近推荐人关注
-(void)addLink:(UIButton *)sender
{
    [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"chuliNotice", nil) activityAnimated:YES];
    NSInteger row = sender.tag-222;
    _linkRow = row;
    NSString *action = @"link";
    NSMutableDictionary *pars = [NSMutableDictionary dictionaryWithCapacity:2];
    [pars setValue:[[_recommendVipArr objectAtIndex:row] valueForKey:@"userid"] forKey:LinkTouID];
    [pars setValue:action forKey:Action];
    [AppComManager getBanBuData:BanBu_Set_Friend_Link par:pars delegate:self];
    self.view.userInteractionEnabled = NO;
}
#pragma mark -
#pragma mark small listview delegate
- (void)smallListView:(BanBu_SmallListView *)smallListView didSelectIndex:(NSInteger)index
{
    [smallListView dismissWithAnimation:YES];
    _listType = index;
}

#pragma mark -
#pragma mark gridCell delegate

- (void)gridCell:(BanBu_GridCell *)cell didSelectedTile:(NSInteger)tileIndex realRow:(NSInteger)row
{
    NSDictionary *buddy = [MyAppDataManager.nearBuddys objectAtIndex:row];
    BanBu_PersonDataViewController *peopleFfofile = [[BanBu_PersonDataViewController alloc] initWithProfile:[buddy valueForKey:keyPersonalInfo]];
    [self.leveyTabBarController hidesTabBar:YES animated:NO];
    [self.navigationController pushViewController:peopleFfofile animated:YES];
    [peopleFfofile release];
}

- (void)banBu_LocationManager:(BanBu_LocationManager *)manager didGetLocation:(CLLocationCoordinate2D)coordinate success:(BOOL)success
{
    if(success)
    {
        if(_currentPage>3)
        {
            return;
        }
        [self setRefreshing];
        AppLocationManager.delegate = nil;
    }
    else
    {
        //        showNoLocationNotice = YES;
        [self.tableView reloadData];
    }
}

- (void)banBu_LocationManager:(BanBu_LocationManager *)manager didGetLocationAddr:(NSString *)addr
{
    if(!_locationTip)
        return;
    
    UILabel *tipView = _locationTip;
    _locationTip = nil;
    
    UIActivityIndicatorView *hua = (UIActivityIndicatorView *)[tipView viewWithTag:HuaTag];
    [hua removeFromSuperview];
    NSString *tip = nil;
    if(addr)
        tip = [NSString stringWithFormat:@"%@%@",NSLocalizedString(@"tipNotice", nil),addr];
    else
        tip =NSLocalizedString(@"tipNotice1", nil);
    tipView.text = tip;
    [UIView animateWithDuration:.5
                          delay:2.0
                        options:0
                     animations:^{
                         tipView.frame = CGRectMake(0, 34, 320, 30);
                     } completion:^(BOOL finished) {
                         [tipView removeFromSuperview];
                     }];
}

- (void)loadingData
{
    segmentController.userInteractionEnabled = NO;
    
    if([self.view viewWithTag:100])
    {
        [[self.view viewWithTag:100]removeFromSuperview];
    }
    if([self.view viewWithTag:101])
    {
        [[self.view viewWithTag:101]removeFromSuperview];
    }
    if(_isLoadingRefresh)
    {
        lab.text = NSLocalizedString(@"pullLoadMore", nil);
        [loadingView stopAnimating];
        [AppComManager cancalHandlesForObject:self];
        AppLocationManager.delegate = self;
        [AppLocationManager getMyLocation];
        _currentPage = 1;
    }
    else{
        if(_currentPage == 1)
        {
            _currentPage = 3;
        }
        else
            _currentPage ++;
    }
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    //        [parDic setValue:[NSString stringWithFormat:@"%i",_listType] forKey:ListKey];
    [parDic setValue:[NSString stringWithFormat:@"%.f",AppLocationManager.curLocation.latitude*1000000] forKey:Latitude];
    [parDic setValue:[NSString stringWithFormat:@"%.f",AppLocationManager.curLocation.longitude*1000000] forKey:Longitude];
    
    [parDic setValue:[NSString stringWithFormat:@"%i",_currentPage] forKey:PageNo];
    
    [parDic setValue:[MyAppDataManager getLanguageSubmitToServer] forKey:@"lang"];
    // 判断有没有这个
    
    if([UserDefaults valueForKey:[NSString stringWithFormat:@"%@electNearBy",MyAppDataManager.useruid]])
    {
        NSMutableDictionary *ob= [UserDefaults valueForKey:[NSString stringWithFormat:@"%@electNearBy",MyAppDataManager.useruid]];
        if(segmentController.selectedIndex == 0)
        {
            NSMutableDictionary *dict=[[NSMutableDictionary alloc]init];
            
            switch ([[ob valueForKey:@"time"] intValue]) {
                case 0:
                    
                    [dict setValue:@"60" forKey:@"lasttime"];
                    
                    break;
                case 1:
                    
                    [dict setValue:@"360" forKey:@"lasttime"];
                    break;
                case 2:
                    [dict setValue:@"1440" forKey:@"lasttime"];
                    break;
                case 3:
                    [dict setValue:@"4320" forKey:@"lasttime"];
                    break;
                default:
                    
                    break;
            }
            
            switch ([[ob valueForKey:@"sex"] intValue]) {
                case 0:
                    
                    [dict setValue:@"" forKey:@"gender"];
                    break;
                case 1:
                    
                    [dict setValue:@"m" forKey:@"gender"];
                    break;
                    
                case 2:
                    
                    [dict setValue:@"f" forKey:@"gender"];
                    
                    break;
                    
                default:
                    break;
            }
            
            switch ([[ob valueForKey:@"age"] intValue]) {
                case 0:
                    
                    [dict setValue:@"" forKey:@"ageof"];
                    break;
                case 1:
                    
                    [dict setValue:@"1" forKey:@"ageof"];
                    break;
                    
                case 2:
                    
                    [dict setValue:@"2" forKey:@"ageof"];
                    break;
                case 3:
                    
                    [dict setValue:@"3" forKey:@"ageof"];
                    break;
                case 4:
                    
                    [dict setValue:@"4" forKey:@"ageof"];
                    break;
                default:
                    break;
            }
            NSArray *arr = [NSArray arrayWithObjects:@"",@"aqu",@"pis",@"ari",@"tau",@"gem",@"can",@"leo",@"vir",@"lib",@"sco",@"sag",@"cap", nil];
            [dict setValue:[arr objectAtIndex:[[ob valueForKey:@"star"] integerValue]] forKey:@"starof"];
            [dict setValue:[ob valueForKey:@"vip"] forKey:@"vip"];
            [dict setValue:[ob valueForKey:@"verify"] forKey:@"verify"];
            [dict setValue:[ob valueForKey:@"area"] forKey:@"area"];
            [parDic setValue:dict forKey:@"searchby"];
            [dict release];
        }
        else
        {
            [parDic setValue:[ob valueForKey:@"orderby"] forKey:@"orderby"];
        }
        
    }
    //    NSLog(@"1111111111111111111111%@",parDic);
    switch (segmentController.selectedIndex) {
        case 1:
            [parDic setValue:@"gh" forKey:@"linkkind"];
            [AppComManager getBanBuData:BanBu_Get_User_Nearmy par:parDic delegate:self];
            break;
            
        case 0:
            [AppComManager getBanBuData:BanBu_Get_User_Nearby par:parDic delegate:self];
            break;
            
        default:
            break;
    }
    
    NSLog(@"%@",parDic);
}
-(void)setSegmentUserInterface
{
    segmentController.userInteractionEnabled = YES;
}

- (void)gotoRecomment
{
    BanBu_RecomViewController *re = [[BanBu_RecomViewController alloc] init];
    [self.navigationController pushViewController:re animated:YES];
    [re release];
    [self.leveyTabBarController hidesTabBar:YES animated:YES];
}
- (void)showInviteFriendEnable
{
    if(MyAppDataManager.nearBuddys.count < 10&&segmentController.selectedIndex == 1&&!showInviteFriend)
    {
        //隐藏好友
        showInviteFriend = NO;
        //        showInviteFriend = YES;
        [self.tableView reloadData];
    }
    else
    {
        showInviteFriend = NO;
    }
}
- (void)updateNoFriendView
{
    
    if(MyAppDataManager.nearBuddys.count < 10&&segmentController.selectedIndex == 1)
    {
        if(MyAppDataManager.nearBuddys.count>0)
        {
            NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
            [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
            NSString *last = [UserDefaults valueForKey:@"lastshow"];
            
            [UserDefaults setValue:[formatter stringFromDate:[NSDate date]] forKey:@"lastshow"];
        }
    }
}


-(void)startLoadNextPage
{
    if(cacheArray.count)
    {
        isLoading = YES;
        NSIndexPath *indexPath;
        if(_sortByList)
            indexPath = [NSIndexPath indexPathForRow:[MyAppDataManager.nearBuddys count] inSection:1];
        else if(cacheArray.count>4)
        {
            indexPath = [NSIndexPath indexPathForRow:MyAppDataManager.nearBuddys.count/4+1 inSection:1];
        }
        else
        {
            indexPath = [NSIndexPath indexPathForRow:MyAppDataManager.nearBuddys.count/4 inSection:1];
        }
        //        NSLog(@"%@",indexPath);
        [MyAppDataManager.nearBuddys addObjectsFromArray:cacheArray];
        [cacheArray removeAllObjects];
        [UIView animateWithDuration:0.5 animations:^{
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
                [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
                isLoading = NO;
            });
        }];
        alreadyRefresh = YES;
    }
    if(!cacheArray.count)
    {
        [self loadingData];
        isLoading = YES;
        segmentController.userInteractionEnabled = NO;
    }
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if([keyPath isEqual:@"contentOffset"])
    {
        //        NSLog(@"%f %f",self.tableView.contentOffset.y,self.tableView.contentSize.height-__MainScreen_Height+44+30);
        if(_isLoadingRefresh)
        {
            [loadingView stopAnimating];
            lab.text = NSLocalizedString(@"pullLoadMore", nil);
        }
        if(![lab.text isEqual:NSLocalizedString(@"loadingMore", nil)]&&self.tableView.contentOffset.y>self.tableView.contentSize.height-__MainScreen_Height+44+30&&MyAppDataManager.nearBuddys.count>=20&&self.tableView.contentOffset.y>0)
        {
            if(!isLoading&&!_isLoadingRefresh)
            {
                //                NSLog(@"开始加载——————————");
                alreadyRefresh = NO;
                _isLoadingRefresh = NO;
                [loadingView startAnimating];
                lab.text = NSLocalizedString(@"loadingNotice", nil);
                //                [self startLoadNextPage];
                [self performSelector:@selector(startLoadNextPage) withObject:nil afterDelay:0.2];
                isLoading = YES;
                segmentController.userInteractionEnabled = NO;
            }
            
            else
            {
                alreadyRefresh = NO;
            }
        }
        else if(MyAppDataManager.nearBuddys.count<20)
        {
            self.tableView.tableFooterView = [[[UIView alloc] initWithFrame:moreView.frame] autorelease];
        }
    }
}

#pragma mark -
#pragma mark AKSegmentedControlDelegate

- (void)segmentedViewController:(AKSegmentedControl *)segmentedControl touchedAtIndex:(NSUInteger)index
{
    switch (index) {
        case 0:
            break;
        case 1:
        {
            followOnline.hidden = YES;
        }
            break;
            
        case 2:
        {
            friendOnline.hidden = YES;
        }
            break;
        default:
            break;
    }
    if(index!=selectIndex)
    {
        selectIndex = index;
        [self buildLeftButton];
        if(selectIndex == 1)
        {
            //            NSString *path = [DataCachePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@-nearbuddydata",MyAppDataManager.useruid]];
            //            [MyAppDataManager.nearBuddys addObjectsFromArray:[NSKeyedUnarchiver unarchiveObjectWithData:[NSData dataWithContentsOfFile:path]]];
            [self.tableView reloadData];
        }
        
        [self setRefreshing];
        
        
    }
    else
    {
        
    }
}
-(void)inviteFriend
{
    
    CFErrorRef myError = NULL;
    ABAddressBookRef myAddressBook = ABAddressBookCreateWithOptions(NULL, &myError);
    NSLog(@"获取通讯录。。。。。");
    if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined)
    {
        ABAddressBookRequestAccessWithCompletion(myAddressBook, ^(bool granted, CFErrorRef error)
                                                 {
                                                     [self getMyAddressBook:myAddressBook];
                                                 });
    }
    else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized)
    {
        [self getMyAddressBook:myAddressBook];
    }
    else
    {
        // The user has previously denied access // Send an alert telling user to change privacy setting in settings app
    }
}
- (void)getMyAddressBook:(ABAddressBookRef) myAddressBook
{
    NSLog(@"获取通讯录。。。。。");
    CFArrayRef results = ABAddressBookCopyArrayOfAllPeople(myAddressBook);
    //        NSString *text = @"";
    NSMutableArray *allPersonArray = [NSMutableArray arrayWithCapacity:0];
    
    for(int i = 0; i < CFArrayGetCount(results); i++)
    {
        NSMutableDictionary *aPersonDic = [NSMutableDictionary dictionaryWithCapacity:0];
        ABRecordRef person = CFArrayGetValueAtIndex(results, i);
        //读取firstname
        NSString *personName = (NSString*)ABRecordCopyValue(person, kABPersonFirstNameProperty);
        if(personName != nil)
            [aPersonDic setValue:personName forKey:@"personName"];
        
        
        //读取lastname
        NSString *lastname = (NSString*)ABRecordCopyValue(person, kABPersonLastNameProperty);
        if(lastname != nil)
            [aPersonDic setValue:lastname forKey:@"lastname"];
        
        //读取middlename
        NSString *middlename = (NSString*)ABRecordCopyValue(person, kABPersonMiddleNameProperty);
        if(middlename != nil)
            [aPersonDic setValue:middlename forKey:@"middlename"];
        //读取prefix前缀
        NSString *prefix = (NSString*)ABRecordCopyValue(person, kABPersonPrefixProperty);
        if(prefix != nil)
            [aPersonDic setValue:prefix forKey:@"prefix"];
        //读取suffix后缀
        NSString *suffix = (NSString*)ABRecordCopyValue(person, kABPersonSuffixProperty);
        
        
        if(suffix != nil)
            [aPersonDic setValue:suffix forKey:@"suffix"];
        //读取nickname呢称
        NSString *nickname = (NSString*)ABRecordCopyValue(person, kABPersonNicknameProperty);
        if(nickname != nil)
            [aPersonDic setValue:nickname forKey:@"nickname"];
        //读取firstname拼音音标
        NSString *firstnamePhonetic = (NSString*)ABRecordCopyValue(person, kABPersonFirstNamePhoneticProperty);
        if(firstnamePhonetic != nil)
            [aPersonDic setValue:firstnamePhonetic forKey:@"firstnamePhonetic"];
        //读取lastname拼音音标
        NSString *lastnamePhonetic = (NSString*)ABRecordCopyValue(person, kABPersonLastNamePhoneticProperty);
        if(lastnamePhonetic != nil)
            [aPersonDic setValue:lastnamePhonetic forKey:@"lastnamePhonetic"];
        //读取middlename拼音音标
        NSString *middlenamePhonetic = (NSString*)ABRecordCopyValue(person, kABPersonMiddleNamePhoneticProperty);
        if(middlenamePhonetic != nil)
            [aPersonDic setValue:middlenamePhonetic forKey:@"middlenamePhonetic"];
        
        
        //读取organization公司
        NSString *organization = (NSString*)ABRecordCopyValue(person, kABPersonOrganizationProperty);
        if(organization != nil)
            [aPersonDic setValue:organization forKey:@"organization"];
        //读取jobtitle工作
        NSString *jobtitle = (NSString*)ABRecordCopyValue(person, kABPersonJobTitleProperty);
        if(jobtitle != nil)
            [aPersonDic setValue:jobtitle forKey:@"jobtitle"];
        //读取department部门
        NSString *department = (NSString*)ABRecordCopyValue(person, kABPersonDepartmentProperty);
        if(department != nil)
            [aPersonDic setValue:department forKey:@"department"];
        //读取birthday生日
        NSDate *birthday = (NSDate*)ABRecordCopyValue(person, kABPersonBirthdayProperty);
        if(birthday != nil)
            [aPersonDic setValue:[NSString stringWithFormat:@"%@",birthday] forKey:@"birthday"];
        //读取note备忘录
        NSString *note = (NSString*)ABRecordCopyValue(person, kABPersonNoteProperty);
        
        if(note != nil)
            [aPersonDic setValue:note forKey:@"note"];
        
        //第一次添加该条记录的时间
        NSString *firstknow = (NSString*)ABRecordCopyValue(person, kABPersonCreationDateProperty);
        [aPersonDic setValue:[NSString stringWithFormat:@"%@",firstknow] forKey:@"firstknow"];
        NSLog(@"第一次添加该条记录的时间%@\n",firstknow);
        
        //最后一次修改該条记录的时间
        NSString *lastknow = (NSString*)ABRecordCopyValue(person, kABPersonModificationDateProperty);
        [aPersonDic setValue:[NSString stringWithFormat:@"%@",lastknow] forKey:@"lastknow"];
        NSLog(@"最后一次修改該条记录的时间%@\n",lastknow);
        
        
        //获取email多值
        ABMultiValueRef email = ABRecordCopyValue(person, kABPersonEmailProperty);
        int emailcount = ABMultiValueGetCount(email);
        NSMutableArray *emailArr = [NSMutableArray arrayWithCapacity:0];
        for (int x = 0; x < emailcount; x++)
        {
            //获取email Label
            NSString* emailLabel = (NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(email, x));
            //获取email值
            NSString* emailContent = (NSString*)ABMultiValueCopyValueAtIndex(email, x);
            emailContent = [emailContent stringByAppendingFormat:@"%@:%@\n",emailLabel,emailContent];
            [emailArr addObject:emailContent];
        }
        [aPersonDic setValue:emailArr forKey:@"emailArr"];
        
        //读取地址多值
        ABMultiValueRef address = ABRecordCopyValue(person, kABPersonAddressProperty);
        int count = ABMultiValueGetCount(address);
        NSMutableArray *addressArr = [NSMutableArray arrayWithCapacity:0];
        for(int j = 0; j < count; j++)
        {
            //获取地址Label
            NSString* addressLabel = (NSString*)ABMultiValueCopyLabelAtIndex(address, j);
            [addressArr addObject:addressLabel];
            //                text = [text stringByAppendingFormat:@"%@\n",addressLabel];
            //                //获取該label下的地址6属性
            //                NSDictionary* personaddress =(NSDictionary*) ABMultiValueCopyValueAtIndex(address, j);
            //                NSString* country = [personaddress valueForKey:(NSString *)kABPersonAddressCountryKey];
            //                if(country != nil)
            //                    text = [text stringByAppendingFormat:@"国家：%@\n",country];
            //                NSString* city = [personaddress valueForKey:(NSString *)kABPersonAddressCityKey];
            //                if(city != nil)
            //                    text = [text stringByAppendingFormat:@"城市：%@\n",city];
            //                NSString* state = [personaddress valueForKey:(NSString *)kABPersonAddressStateKey];
            //                if(state != nil)
            //                    text = [text stringByAppendingFormat:@"省：%@\n",state];
            //                NSString* street = [personaddress valueForKey:(NSString *)kABPersonAddressStreetKey];
            //                if(street != nil)
            //                    text = [text stringByAppendingFormat:@"街道：%@\n",street];
            //                NSString* zip = [personaddress valueForKey:(NSString *)kABPersonAddressZIPKey];
            //                if(zip != nil)
            //                    text = [text stringByAppendingFormat:@"邮编：%@\n",zip];
            //                NSString* coutntrycode = [personaddress valueForKey:(NSString *)kABPersonAddressCountryCodeKey];
            //                if(coutntrycode != nil)
            //                    text = [text stringByAppendingFormat:@"国家编号：%@\n",coutntrycode];
        }
        [aPersonDic setValue:addressArr forKey:@"addressArr"];
        //            //获取dates多值
        //            ABMultiValueRef dates = ABRecordCopyValue(person, kABPersonDateProperty);
        //            int datescount = ABMultiValueGetCount(dates);
        //            for (int y = 0; y < datescount; y++)
        //            {
        //                //获取dates Label
        //                NSString* datesLabel = (NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(dates, y));
        //                //获取dates值
        //                NSString* datesContent = (NSString*)ABMultiValueCopyValueAtIndex(dates, y);
        //                [aPersonDic setValue:[NSString stringWithFormat:@"%@:%@",datesLabel,datesContent] forKey:@"datesContent"];
        ////                text = [text stringByAppendingFormat:@"%@:%@\n",datesLabel,datesContent];
        //            }
        //            //获取kind值
        //            CFNumberRef recordType = ABRecordCopyValue(person, kABPersonKindProperty);
        //            if (recordType == kABPersonKindOrganization) {
        //                // it's a company
        //                NSLog(@"it's a company\n");
        //            } else {
        //                // it's a person, resource, or room
        //                NSLog(@"it's a person, resource, or room\n");
        //            }
        
        
        //获取IM多值
        
        ABMultiValueRef instantMessage = ABRecordCopyValue(person, kABPersonInstantMessageProperty);
        NSMutableArray *instantMessageArr = [NSMutableArray arrayWithCapacity:0];
        for (int l = 1; l < ABMultiValueGetCount(instantMessage); l++)
        {
            //获取IM Label
            NSString* instantMessageLabel = (NSString*)ABMultiValueCopyLabelAtIndex(instantMessage, l);
            [instantMessageArr addObject:instantMessageLabel];
            //                text = [text stringByAppendingFormat:@"%@\n",instantMessageLabel];
            
            //                //获取該label下的2属性
            //                NSDictionary* instantMessageContent =(NSDictionary*) ABMultiValueCopyValueAtIndex(instantMessage, l);
            //                NSString* username = [instantMessageContent valueForKey:(NSString *)kABPersonInstantMessageUsernameKey];
            //                if(username != nil)
            //                [aPersonDic setValue:username forKey:@"username"];
            //
            //                NSString* service = [instantMessageContent valueForKey:(NSString *)kABPersonInstantMessageServiceKey];
            //                if(service != nil)
            //                [aPersonDic setValue:service forKey:@"service"];
            
        }
        [aPersonDic setValue:instantMessageArr forKey:@"instantMessageArr"];
        //读取电话多值
        ABMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty);
        NSMutableArray *phoneNumberArr = [NSMutableArray arrayWithCapacity:0];
        for (int k = 0; k<ABMultiValueGetCount(phone); k++)
        {
            //获取电话Label
            NSString * personPhoneLabel = (NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(phone, k));
            //获取該Label下的电话值
            NSString * personPhone = (NSString*)ABMultiValueCopyValueAtIndex(phone, k);
            [phoneNumberArr addObject:[NSString stringWithFormat:@"%@",personPhone]];
            //                text = [text stringByAppendingFormat:@"%@:%@\n",personPhoneLabel,personPhone];
        }
        [aPersonDic setValue:phoneNumberArr forKey:@"phoneNumberArr"];
        //获取URL多值
        ABMultiValueRef url = ABRecordCopyValue(person, kABPersonURLProperty);
        NSMutableArray *urlcontentArr = [NSMutableArray arrayWithCapacity:0];
        for (int m = 0; m < ABMultiValueGetCount(url); m++)
        {
            //获取电话Label
            NSString * urlLabel = (NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(url, m));
            //获取該Label下的电话值
            NSString * urlContent = (NSString*)ABMultiValueCopyValueAtIndex(url,m);
            [urlcontentArr addObject:[NSString stringWithFormat:@"%@:%@\n",urlLabel,urlContent]];
            //                text = [text stringByAppendingFormat:@"%@:%@\n",urlLabel,urlContent];
        }
        [aPersonDic setValue:urlcontentArr forKey:@"urlcontentArr"];
        
        [allPersonArray addObject:aPersonDic];
        //读取照片
        //            NSData *image = (NSData*)ABPersonCopyImageData(person);
        
        //            UIImageView *myImage = [[UIImageView alloc] initWithFrame:CGRectMake(200, 0, 50, 50)];
        //            [myImage setImage:[UIImage imageWithData:image]];
        //            myImage.opaque = YES;
        //            [textView addSubview:myImage];
        //
    }
    //    NSLog(@"%@",allPersonArray);
    //    NSString *allPersonJson = [[CJSONSerializer serializer] serializeArray:allPersonArray];
    
    
    
    NSError *error;
    NSData *allPersonJson = nil;
    if ([NSJSONSerialization isValidJSONObject:allPersonArray])
    {
        allPersonJson = [NSJSONSerialization dataWithJSONObject:allPersonArray options:NSJSONWritingPrettyPrinted error:&error];
        [AppComManager getBanBuData:BanBu_Set_User_Phonelist par:[NSDictionary dictionaryWithObjectsAndKeys:[[NSString alloc] initWithData:allPersonJson encoding:NSUTF8StringEncoding],@"phonelist",@" ",@"myphone",nil] delegate:nil];
    }
    
    
    
    CFRelease(results);
    CFRelease(myAddressBook);
    
    
    NSMutableArray *perosonList = [NSMutableArray arrayWithCapacity:0];
    NSLog(@"%@",allPersonArray);
    for(NSDictionary *p in allPersonArray)
    {
        //        NSLog(@"%@",p);
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        NSString *firstName = [p valueForKey:@"personName"];
        NSString *lastName  = [p valueForKey:@"lastname"];
        NSMutableString *name = [NSMutableString string];
        if(![[MyAppDataManager getLanguageSubmitToServer] isEqualToString:@"cn"]&&![[MyAppDataManager getLanguageSubmitToServer] isEqualToString:@"hk"])
        {
            if(firstName.length) { [name appendString:firstName]; }
            
            if(lastName.length)  { [name appendString:lastName]; }
        }
        else
        {
            if(lastName.length)  { [name appendString:lastName]; }
            
            if(firstName.length) { [name appendString:firstName]; }
        }
        
        
        [dic setValue:name forKey:@"personName"];
        [dic setValue:[p valueForKey:@"phoneNumberArr"] forKey:@"phoneNumberArr"];
        [perosonList addObject:dic];
    }
    
    //    NSMutableArray *perosonList = [NSMutableArray arrayWithCapacity:0];
    //    for (int i = 0; i<20; i++) {
    //        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    //        [dic setValue:[NSString stringWithFormat:@"%d",i] forKey:@"personName"];
    //        [dic setValue:@[@"13515346542",@"14573289929"] forKey:@"phoneNumberArr"];
    //        [perosonList addObject:dic];
    //    }
    
    
    BanBu_InviteFriendViewController *invite = [[BanBu_InviteFriendViewController alloc] initWithDataArray:perosonList];
    [self.navigationController pushViewController:invite animated:YES];
    [invite release];
    [self.leveyTabBarController hidesTabBar:YES animated:YES];
}
@end